package com.school.aftersalemanagement.controller.ui.main;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.school.aftersalemanagement.R;
import com.school.aftersalemanagement.entity.Bike;
import com.school.aftersalemanagement.service.BicycleService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by winkyle on 2017/11/6.
 */

public class Map implements
        AMapLocationListener,
        AMap.OnCameraChangeListener,
        AMap.InfoWindowAdapter,
        AMap.OnMapClickListener,
        AMap.OnMarkerClickListener,
        AMap.OnInfoWindowClickListener,
        LocationSource {
    private Context context;
    private MapFragment mapfragment;
    private double getMeLon;//获取定位纬度
    private double getMeLat;//获取定位经度
    private double getCameraLat;//获取视角纬度
    private double getCameraLon;//获取视角经度

    public Map(Context context,MapFragment mapfragment){
        this.context = context;
        this.mapfragment = mapfragment;
    }

    //地图中心移动中
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    //地图中心移动结束
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLng target = cameraPosition.target;

        getCameraLat = target.latitude;
        getCameraLon = target.longitude;
        if(ShowInfoWindow) {
            mapfragment.getBicycleList();
        }else{
            ShowInfoWindow = true;
        }
    }

    private AMapLocationClient mlocationClient;
    private OnLocationChangedListener mListener;

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(context);
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            mLocationOption.setOnceLocation(false);
            /*
             * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
             * 注意：只有在高精度模式下的单次定位有效，其他方式无效
             */
            mLocationOption.setGpsFirst(true);
            // 设置发送定位请求的时间间隔,最小值为1000ms,10秒更新一次定位信息
            mLocationOption.setInterval(1000);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        }
        mlocationClient.startLocation();
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    private boolean first = true;
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                getMeLat = aMapLocation.getLatitude();//获取纬度
                getMeLon = aMapLocation.getLongitude();//获取经度
                //第一次定位，将视角移到此点
                if(first){
                    first = false;
                    setLocation();
                }
                Log.d("定位", "latitude:" + getMeLat + "longitude:" + getMeLon);
            }

        }
    }
    View infoWindow = null;
    @Override
    public View getInfoWindow(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(context).inflate(
                    R.layout.infowindow_mark, null);
        }
        Log.d("RequestCall","getInfoWindow");
        render(marker, infoWindow);
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(context).inflate(
                    R.layout.infowindow_mark, null);
        }
        Log.d("RequestCall","getInfoContents");
        render(marker, infoWindow);
        return infoWindow;
    }

    public void render(final Marker marker, View view) {
        final Bike bike = (Bike)marker.getObject();
        //如果想修改自定义Infow中内容，请通过view找到它并修改
        TextView info_bicycle;
        TextView info_adress;
        TextView info_date;
        TextView info_person;
        TextView info_rideTimes;
        TextView info_afterTimes;
        TextView info_failreportinglist;
        TextView info_remarklist;

        TextView info_battery;
        TextView info_longLease;
        TextView info_leaseStatus;
        info_bicycle = (TextView) view.findViewById(R.id.info_bicycle);
        info_adress = (TextView) view.findViewById(R.id.info_adress);
        info_date = (TextView) view.findViewById(R.id.info_date);
        info_person = (TextView) view.findViewById(R.id.info_person);
        info_rideTimes = (TextView) view.findViewById(R.id.info_rideTimes);
        info_afterTimes = (TextView) view.findViewById(R.id.info_afterTimes);
        info_failreportinglist = (TextView) view.findViewById(R.id.info_failreportinglist);
        info_remarklist = (TextView) view.findViewById(R.id.info_remarklist);
        info_battery = (TextView) view.findViewById(R.id.info_battery);
        info_longLease = (TextView) view.findViewById(R.id.info_longLease);
        info_leaseStatus = (TextView) view.findViewById(R.id.info_leaseStatus);
        info_bicycle.setText(bike.getTypeName()+"："+bike.getNumber());
        info_adress.setText("地址："+bike.getAddress());
        SimpleDateFormat sdf= new SimpleDateFormat("MM-dd HH:mm");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = "";
        try {
            if((!(bike.getRepair_time()==null))&&(!"".equals(bike.getRepair_time())))
                date = sdf.format(format.parse(bike.getRepair_time()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        info_date.setText("上次保养："+date);
        info_person.setText("保养人："+bike.getRepair_person() );
        info_rideTimes.setText("总骑行数："+bike.getRiding_times()+"次");
        info_afterTimes.setText("养后次数："+bike.getRepaired_rtimes()+"次");
        info_failreportinglist.setText("故障"+bike.getFailreporting().toString());
        info_remarklist.setText("备注："+bike.getRemark());
        info_battery.setText("电量:"+bike.getBaterry());
        info_longLease.setText("长租:"+bike.getLong_lease());
        info_leaseStatus.setText("租借:"+bike.getLease_status());
        TextView info_maintance;
        TextView info_remark;
        TextView info_openLock;
        TextView info_edit;
        info_maintance = (TextView) view.findViewById(R.id.info_maintance);
        info_remark = (TextView) view.findViewById(R.id.info_remark);
        info_openLock = (TextView) view.findViewById(R.id.info_openLock);
        info_edit = (TextView) view.findViewById(R.id.info_edit);
        info_maintance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(context).setTitle("保养提示")//对话框标题
                        .setMessage("是否确认保养？")//对话框提示正文
                        .setIcon(R.mipmap.ic_launcher)//对话框标题上的图片
                        .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override//取消按钮
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context, "取消保养", Toast.LENGTH_SHORT).show();
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override//确定按钮
                    public void onClick(DialogInterface dialog, int which) {
                        mapfragment.mainTenance(bike.getNumber());
                    }
                }).setCancelable(false)//点击其他区域关闭对话框
                        .show();
            }
        });
        info_remark.setOnClickListener(new View.OnClickListener() {
            final EditText inputServer = new EditText(context);
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(context).setTitle("备注提示")//对话框标题
                        .setView(inputServer)//对话框提示正文
                        .setIcon(R.mipmap.ic_launcher)//对话框标题上的图片
                        .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override//取消按钮
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context, "取消备注", Toast.LENGTH_SHORT).show();
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override//确定按钮
                    public void onClick(DialogInterface dialog, int which) {
                        mapfragment.setRemark(bike.getNumber(),inputServer.getText().toString());
                    }
                }).setCancelable(false)//点击其他区域关闭对话框
                        .show();
            }
        });
        info_openLock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(context).setTitle("保养提示")//对话框标题
                        .setMessage("是否开锁？")//对话框提示正文
                        .setIcon(R.mipmap.ic_launcher)//对话框标题上的图片
                        .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override//取消按钮
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context, "取消开锁", Toast.LENGTH_SHORT).show();
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override//确定按钮
                    public void onClick(DialogInterface dialog, int which) {
                        mapfragment.serviceUnlock(bike.getNumber());
                    }
                }).setCancelable(false)//点击其他区域关闭对话框
                        .show();
            }
        });
        info_edit.setOnClickListener(new View.OnClickListener() {
            String[] operate;
            @Override
            public void onClick(View v) {
                if(bike.getLease_status()==0)
                    operate = new String[]{"清除故障状态","车辆写死","返回"};
                else if(bike.getLease_status()==1)
                    operate = new String[]{"清除故障状态","车辆写活","返回"};
                new AlertDialog.Builder(context).setTitle("请选择编辑操作")//对话框标题
                        .setItems(operate,new DialogInterface.OnClickListener() {
                            @Override//取消按钮
                            public void onClick(DialogInterface dialog, int which) {
                                switch(which){
                                    case 0:
                                        mapfragment.solveProblem(bike.getNumber());
                                        break;
                                    case 1:
                                        int status = 1;
                                        if(bike.getLease_status()==0)
                                            status = 1;
                                        else if(bike.getLease_status()==1)
                                            status = 0;
                                        mapfragment.lockBike(bike.getNumber(),status);
                                        break;
                                    case 2:
                                        Toast.makeText(context, "取消编辑", Toast.LENGTH_SHORT).show();
                                        break;
                                }
                            }
                        })//对话框提示正文
                        .setIcon(R.mipmap.ic_launcher)//对话框标题上的图片
                        .setCancelable(false)//点击其他区域关闭对话框
                        .show();
            }
        });
    }


    @Override
    public void onInfoWindowClick(Marker marker) {
        if (currentMarker.isInfoWindowShown()) {
            currentMarker.hideInfoWindow();//这个是隐藏infowindow窗口的方法
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (currentMarker != null) {
            currentMarker.hideInfoWindow();//这个是隐藏infowindow窗口的方法
        }
    }

    Marker currentMarker;
    @Override
    public boolean onMarkerClick(Marker marker) {
        currentMarker = marker;
        getInfoContents(marker);
        marker.showInfoWindow();
        return true;
    }

    private AMap aMap;
    public void intiMap(MapView mMapView) {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setOnCameraChangeListener(this); //设置摄像机视角监听
        aMap.setOnMapClickListener(this);//地图监听
        aMap.setInfoWindowAdapter(this);//弹窗样式
        aMap.setOnMarkerClickListener(this);//Mark点击监听
        aMap.setOnInfoWindowClickListener(this);//弹窗点击监听
        aMap.getUiSettings().setMyLocationButtonEnabled(false);//定位按钮不可见
        aMap.getUiSettings().setZoomControlsEnabled(false);//缩放按钮不可见
    }

    private boolean ShowInfoWindow = true;
    public void refreshMarket(List<Bike> bikes){
        aMap.clear();
        Marker marker = null;
        if(!bikes.isEmpty()) {
            //循环添加自定义点mark
            for (int i = 0; i < bikes.size(); i++) {
                marker = aMap.addMarker(getMarkerOption(bikes.get(i)));
                marker.setObject(bikes.get(i));
            }
            if (bikes.size() <= 1) {
                ShowInfoWindow = false;
                CameraUpdate cameraUpdate = CameraUpdateFactory
                        .newCameraPosition(new CameraPosition(new LatLng(bikes.get(0).getLat(), bikes.get(0).getLog()), 16, 0, 0));
                if (aMap != null) aMap.moveCamera(cameraUpdate);
                getInfoContents(marker);
                marker.showInfoWindow();
            }
        }
    }

    private MarkerOptions getMarkerOption(Bike bike){
        LatLng latLng = new LatLng(bike.getLat(), bike.getLog());
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.title("自行车").snippet(bike.getColor());
        markerOption.draggable(false);//设置Marker可拖动
        if ("yellow".equals(bike.getColor())) {
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(context.getResources(), R.drawable.icon_yellow)));
        }else if ("green".equals(bike.getColor())) {
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(context.getResources(), R.drawable.icon_green)));
        } else if ("blue".equals(bike.getColor())) {
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(context.getResources(), R.drawable.icon_blue)));
        } else if ("red".equals(bike.getColor())) {
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(context.getResources(), R.drawable.icon_red)));
        }else if ("rainbow".equals(bike.getColor())) {
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(context.getResources(), R.drawable.icon_rainbow)));
        }else if ("black".equals(bike.getColor())) {
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(context.getResources(), R.drawable.icon_black)));
        }
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        markerOption.visible(true);
        markerOption.position(latLng);
        return markerOption;
    }



    public void setLocation(){
        aMap.clear();
        CameraUpdate cameraUpdate = CameraUpdateFactory
                .newCameraPosition(new CameraPosition(new LatLng(getMeLat, getMeLon), 16, 0, 0));
        if (aMap != null) aMap.moveCamera(cameraUpdate);
    }

    public String getLocation() {
        return getCameraLon+","+getCameraLat;
    }
}
